package com.immac.leejc.bufferedinputstream;

import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;

public class LeeJCBufferedInputStream implements Closeable{
	private InputStream inputStream;
	private byte[] byteBuffer;
	private int bulkSize = 4096;
	private int bufferIndex;
	private boolean isInputStreamReady = true;

	public LeeJCBufferedInputStream (InputStream in) {
		inputStream = in;
		byteBuffer = new byte[bulkSize];
	}

	private void readData() {
		int readDataSize = 0;
		
		if (isInputStreamReady) {
			bufferIndex = 0;
			
			try {
				byte[] bulk = new byte[bulkSize];
				readDataSize = inputStream.read(bulk);
				
				System.arraycopy(bulk, 0, byteBuffer, 0, readDataSize);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		if (readDataSize >= bulkSize) {
			isInputStreamReady = true;
		} else {
			Arrays.fill(byteBuffer, readDataSize, bulkSize - 1, (byte)0);
			isInputStreamReady = false;
		}
	}

	public int read() throws Exception{
		if ((byteBuffer[0] == 0) || (byteBuffer.length == bufferIndex)) {
			readData();
		}
		
		if (byteBuffer[bufferIndex] != 0) {
			return byteBuffer[bufferIndex++];
		} else {
			throw new Exception("더이상 읽을수 없습니다.");
		}
	}

	public void close() {
		try {
			inputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public boolean ready() {
		return (byteBuffer[0] == 0)? false: true;
	}
}
